<?php

namespace app\home\home;
use app\home\model\User;
use phpDocumentor\Reflection\Types\Iterable_;
use think\Db;
use think\Loader;
use think\Request;
include_once EXTEND_PATH.'yunxun/Ucpaas.php';
include_once EXTEND_PATH.'phpqrcode/qrcode.php';
class Users extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {

    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * 用户登录
     *
     * @param  $request 登录数据
     * @return \think\Response
     */
    public function login(Request $request){

        //\Think\Db::table('oa_home_user')->update(['updatetime'=>time()]);
        $data = $request->param();
        $validate = validate('Users');
        $phonenum = $data['phonenum'];
        $isregister = $this->checkPhone($phonenum);
        if (!$isregister)  return apistatus(0,'该手机号未注册');
        if ($isregister['status'] == 0)  return apistatus(0,'您的账户已被禁用，请联系客服');
            if ($data['type'] == 1){
                $res = $validate->scene('loginpwd')->check($data);
                if (!$res){
                    return apistatus(0,$validate->getError());
                }
                if ($isregister['pwd'] !== sha1($data['pwd'])){
                    return apistatus(0,'用户名或密码错误');
                }
                $usercenter=$this->myCenter($isregister['id'],$isregister['role']);
                $today = date('Y-m-d',time());
                $danhao = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
                $api_token = md5('home'.'users'.'login'.$today.$data['pwd'].$danhao);
                $usercenter['usertoken'] = $api_token;
                $usercenter['usertoken_expire'] = time()+604800;
                \Think\Db::table('rd_home_users')
                    ->where('phonenum',$phonenum)
                    ->update(['usertoken'=>$api_token,'usertoken_expire'=>$usercenter['usertoken_expire']]);
                return apistatus(1,'登录成功',$usercenter);

            }else{
                $res = $validate->scene('logincode')->check($data);
                if (!$res){
                    return apistatus(0,$validate->getError());
                }
                $code = $data['code'];
                $oldcode = Db::table('rd_home_code')
                    ->field(['id','code','expire_time','phonenum'])
                    ->where('phonenum',$data['phonenum'])
                    ->where('status',1)
                    ->order('create_time desc')
                    ->find();
                if ($oldcode['phonenum'] !== $data['phonenum']){
                    return apistatus(0,'请输入获取验证码的手机号');
                }
                if (empty($oldcode)){
                    return apistatus(0,'验证码已被使用请重新获取');
                }
                if ( $oldcode['code'] == $code && $oldcode['expire_time']>time()){
                    $usercenter = $this->myCenter($isregister['id'],$isregister['role']);

                    $usercenter['usertoken'] = setToken($data['code']);
                    $usercenter['usertoken_expire'] = time()+604800;
                    \model('user')->where('phonenum',$phonenum)
                        ->update(['usertoken'=>$usercenter['usertoken'],'usertoken_expire'=>$usercenter['usertoken_expire']]);
                    if ($usercenter){
                        //如果用户新建成功获取对应用户信息
                        Db::table('rd_home_code')->where('id',$oldcode['id'])->update(['status'=>2]);
                        return apistatus(1,'登录成功',$usercenter);
                    }
                }else{
                    return apistatus(0,'验证码过期或错误');
                }

            }

    }

    /**
     * 我的

     */
    public  function myCenter($id,$role)
    {
//        $data = $request->param();
//        $validate = validate('Users');
//        $res = $validate->scene('id')->check($data);
//        if (!$res){
//            return apistatus(0,$validate->getError());
//        }
        $where['id'] = $id;
        if ($role == 1){
            $info = \model('User')->where($where)
                ->field('id,headicon,nickname,rd_coin,phonenum,role,operation_time,chattimes,alipaynum,realname')
                ->find()
                ->toarray();
            $info['csquares'] = \db('home_squares')->where(['uid'=>$info['id'],'type'=>4])->count();
            $info['cfriends'] = \db('home_friends')->where(['uid'=>$info['id'],'status'=>1])->count();
            $info['czhouyi'] = \db('home_follow')->alias('F')
                ->join('home_users U','F.followdid=U.id')
                ->where(['F.uid'=>$info['id'],'U.role'=>3])
                ->count();
            $info['ctotur'] = \db('home_follow')->alias('F')
                ->join('home_users U','F.followdid=U.id')
                ->where(['F.uid'=>$info['id'],'U.role'=>2])
                ->count();
            $info['cnews'] = \db('home_news')->where(['toid'=>$info['id'],'status'=>1])
                ->count();
            $info['cmessage'] = countunreadMessage($id);
            $info['cost'] = config('base.web_marriagecost');
            $info['chatcost'] = config('base.web_chatcoin');
        }elseif($role == 2){

            $info = \model('User')->where($where)->field('id,headicon,nickname,phonenum,age,operation_time,rd_coin,role,alipaynum,realname')->find();
            $chatcount = \db('home_chats')->where(['type'=>3,'toid'=>$id])->group('fromid')->count();
            $info['ctotur'] = \db('home_follow')->alias('F')
                ->join('home_users U','F.followdid=U.id')
                ->where(['F.uid'=>$id,'U.role'=>2])
                ->count();
            $info['chatcount'] = $chatcount;
            $info['cnews'] = \db('home_news')->where(['toid'=>$info['id'],'status'=>1])
                ->count();
            $info['cmessage'] = countunreadMessage($id);

//            $info['totur'] = $dynamic->toarray();
        }else{
            $info = \model('User')->where($where)->field('id,headicon,nickname,phonenum,age,operation_time,rd_coin,role,alipaynum,realname')->find();
            $chatcount = \db('home_chats')->where(['type'=>3,'toid'=>$id])->group('fromid')->count();
            $info['ctotur'] = \db('home_follow')->alias('F')
                ->join('home_users U','F.followdid=U.id')
                ->where(['F.uid'=>$id,'U.role'=>2])
                ->count();
            $info['cnews'] = \db('home_news')->where(['toid'=>$info['id'],'status'=>1])
                ->count();
            $info['cmessage'] = countunreadMessage($id);
//            $dynamic = \db('home_squares')
//                ->where(['uid'=>$id,'type'=>2])
//                ->field('id,contents,create_time,skills')
//                ->order('create_time desc')
//                ->paginate(10)
//                ->each(function ($item){
////                    $skills = explode(',',$item['skills']);
//                    $skills = \db('home_taps')->where(['id'=>['in',explode(',',$item['skills'])]])->field('id,name')->select();
//                    $item['skills'] = $skills;
//                    return $item;
//                });
            $info['chatcount'] = $chatcount;
//            $info['totur'] = $dynamic->toarray();
        }
        if (!empty($info)){
            return $info;
        }else{
            return false;
        }
    }
    /**
     * 个人动态列表接口
     *
     * @param  $request发送的请求
     * @return \think\Response
     */
    public function getDynamicList(Request $request){
        $data = $request->param();
        $where['S.uid'] = $data['id'];
        $page = isset($data['page']) ? $data['page'] : 1;
        $listrow = $data['listrow'];
        $desc = "S.create_time desc";
        if (isset($data['type'])){
            if ($data['type'] == 1){
                $where['S.type'] = 1;
                $desc .= ',S.is_top desc';
            }elseif($data['type'] == 4){
                $where['S.type'] = 4;
            }
        }

        $list = \db('home_squares')->alias('S')
                ->join('home_users U','S.uid=U.id')
                ->where($where)
                ->field('S.id,S.uid,U.nickname,U.headicon,U.age,U.gender,S.contents,S.create_time,S.pics1,S.skills,S.saddress')
                ->order($desc)
                ->paginate($listrow,true,['page'=>$page])
                ->each(function ($item){
//                    $skills = explode(',',$item['skills']);
                    $is_praise = isPraise($item['uid'],$item['id']);
                    $item['is_praise'] = $is_praise;
                    $item['countpraise'] = countPraises($item['id']);
                    $item['pics1'] = explode(',',$item['pics1']);
                    $skills = \db('home_taps')->where(['id'=>['in',explode(',',$item['skills'])]])->field('id,name')->select();
                    $item['skills'] = $skills;
                    return $item;
                });
        if ($list){
            return apistatus(1,'列表获取成功',$list);
        }else{
            return apistatus(0,'无数据');
        }
    }
    /**
     * 注册
     *
     * @param  $request发送的请求
     * @return \think\Response
     */
    public function register(Request $request){
        $data = $request->param();
        if ($request->isPost()){

                //自动验证字段是否合规
                $validate = validate('Users');
                if (empty($data['role'])){
                    return apistatus(0,'请选择您需要注册的角色');
                }
                if (!empty($data['invicode'])){
                    $info = \db('home_users')->where('invicode',$data['invicode'])->find();
                    if ($info){
                        $insert['pid'] = $info['id'];
                        $insert['rd_coin'] = config('base.web_invicoin');
                    }
                }
                if ($data['role'] == 1){
                    $res = $validate->scene('registermarr')->check($data);
                    if (!$res){
                        return apistatus(0,$validate->getError());
                    }
                    //婚恋注册数据
                    $insert['jobs'] = $data['jobs'];
                    $insert['salary'] = $data['salary'];
                    $insert['marriage'] = $data['marriage'];
                    $insert['address'] = $data['address'];
                    $insert['monologue'] = $data['monologue'];
                }else{
                    $res = $validate->scene('registertotur')->check($data);
                    if (!$res){
                        return apistatus(0,$validate->getError());
                    }
                    $insert['skills'] = $data['skills'];
                    $insert['introduction'] = $data['introduction'];
                }
                $isregi = $this->checkPhone($data['phonenum']);
                if ($isregi){
                    return apistatus(0,'手机号已注册');
                }

                $code = $data['code'];
                $oldcode = Db::table('rd_home_code')
                    ->field(['id','code','expire_time','phonenum'])
                    ->where('phonenum',$data['phonenum'])
                    ->where('status',1)
                    ->order('create_time desc')
                    ->find();
                if ($oldcode['phonenum'] !== $data['phonenum']){
                    return apistatus(0,'请输入获取验证码的手机号');
                }
                if (empty($oldcode)){
                    return apistatus(0,'验证码已被使用请重新获取');
                }

                $insert['gender'] = $data['gender'];
                $insert['age'] = $data['age'];
                $insert['pwd'] = sha1($data['pwd']);
                isset($data['headicon']) ? $insert['headicon'] = $data['headicon'] : $insert['headicon'] = '/static\home\image\headicon\headicon.jpg';
                $insert['create_time'] = time();
                $insert['operation_time'] = time();
                $insert['nickname'] = $data['nickname'];
                $insert['client_ip'] = $_SERVER['REMOTE_ADDR'];
                $insert['phonenum'] = $data['phonenum'];
                $insert['wechat_num'] = $data['wechat_num'];
                $insert['role'] = $data['role'];
                $insert['invicode'] = randCode();
                //经纬度
                isset($data['longitude']) ? $insert['longitude'] = $data['longitude'] : true;
                isset($data['latitude']) ? $insert['latitude'] = $data['latitude'] : true;
                $insert['usertoken'] =setToken($data['pwd']);
                $insert['usertoken_expire'] = time()+604800;
                if ( $oldcode['code'] == $code && $oldcode['expire_time']>time()){
                    $result = model('user')->insertGetId($insert);
                    if ($result){
                        if ($insert['role'] == 2 || $insert['role'] == 3){
                            $skills = explode(',',$data['skills']);
                            foreach ($skills as $k=>$v){
                               $cost[$k]['cost'] = 200;
                               $cost[$k]['uid'] = $result;
                               $cost[$k]['tapid'] = $v;
                               $cost[$k]['create_time'] = time();
                            }
                           \db('home_tapcost')->insertAll($cost);
                        }
                        if ($insert['role'] == 1 && !empty($insert['rd_coin'])){
                            \db('home_users')->where('id',$info['id'])->setInc('rd_coin',$insert['rd_coin']);
                        }
                        //如果用户新建成功获取对应用户信息
                        $infos = $this->myCenter($result,$insert['role']);
                        Db::table('rd_home_code')->where('id',$oldcode['id'])->update(['status'=>2]);
                        return apistatus(1,'用户新建成功',$infos);
                    }
                }else{
                    return apistatus(0,'验证码过期或错误');
                }

        }else{
            return apistatus(0,'非法请求');
        }
    }


    /**
     * 调用短信发送接口
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function sendMsg(Request $request){

        $data = $request->param();
        $string = "^((13[0-9])|(14[0-9])|(15[0,1,2,3,4,5,6,7,8,9])|(16[0-9])|(19[0-9])|(18[0-9])|(17[0,1,3,5,6,7,8,9]))\\d{8}$^";
        $validate = validate('Users');
        $res = $validate->scene('sendmsg')->check($data);
        if (!$res){
            return apistatus(0,$validate->getError());
        }
        $mathch = preg_match($string,$data['phonenum']);
        if ($mathch){
            //$data['type']1代表注册，2代表忘记密码
            $isregi = $this->checkPhone($data['phonenum']);

            switch ($data['type']){
                case '1' :
                    if ($isregi){
                        return apistatus(0,'该手机号已注册');
                    }
                    break;
                case '2' :
                    if (!$isregi){
                        return apistatus(0,'手机号未注册');
                    }
                    break;
            }

            $code = '';
            for ($i = 0;$i<=5;$i++){
                $code.=rand(0,9);
            }
            $codeinfo['code'] = $code;
            $codeinfo['phonenum'] = $data['phonenum'];
            $codeinfo['create_time'] = time();
            $codeinfo['expire_time'] = time()+3000;
            $where['phonenum'] = $data['phonenum'];
            $todaytime = strtotime(date("Y-m-d",time()));
            $where['create_time'] = ['between',[$todaytime,($todaytime+86400)]];

            $count = Db::table('rd_home_code')->where($where)->count();
            //填写在开发者控制台首页上的Account Sid
            $options = config('msg_config.options');
            $appid = config('msg_config.appid');	//应用的ID，可在开发者控制台内的短信产品下查看
            $templateid = config('msg_config.templateid');
            $uid = '';
            $pcpass = new \Ucpaas($options);//可在后台短信产品→选择接入的应用→短信模板-模板ID，查看该模板ID
            if ($count < 200){
                    Db::table('rd_home_code')->insert($codeinfo);
                    $yresult = $pcpass->SendSms($appid,$templateid,$code,$data['phonenum'],$uid);
                    if (json_decode($yresult)->code == '000000'){
                        return apistatus(1,'验证码获取成功');
                    }elseif(json_decode($yresult)->code == '105147'){
                        return apistatus(0,'短信发送超过限制');
                    }elseif(json_decode($yresult)->code == '105150'){
                        return apistatus(0,'短信发送频率过快');
                    }else{
                        return apistatus(0,'网络错误请重试');
                    }
            }else{
                return apistatus(0,'本日短信验证码次数过多');
            }
        }else{
            return apistatus(0,'手机号格式错误');
        }
    }


    /**
     * 判断手机号是否注册接口
     *
     * @param  int  $id
     * @return \think\Response
     */
    private function checkPhone($phonenum){
        if (!empty($phonenum)){
            $regi = db('home_users')
                ->where('phonenum',$phonenum)
                ->find();
            if ($regi){
                return $regi;
            }else{
                return false;
            }
        }
    }

    /**
     * 我的个人中心
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function getMy(Request $request){
       $data = $request->param();
       self::checktoken($data['id']);
       $role = User::where('id',$data['id'])->find()->getAttr('role');
       $info = $this->myCenter($data['id'],$role);
       return apistatus(1,'信息获取成功',$info);
    }
    /**
     * 记录用户是否操作接口
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function recordOperation(Request $request){
        $data = $request->param();
        if (!empty($data['id'])){
            $update['id'] = $data['id'];
            $update['operation_time'] = time();
            $update['longitude'] = isset($data['longitude']) ? $data['longitude'] : '';
            $update['latitude'] = isset($data['latitude']) ? $data['latitude'] : '';
            $res = User::update($update);
            if ($res){
                return apistatus(1,'操作成功');
            }else{
                return apistatus(0,'操作失败');
            }

        }else{
            return apistatus(0,'缺少用户id');
        }
    }

//    /**
//     * 获取个人技能列表
//     *
//     * @param  int  $id
//     * @return \think\Response
//     */
//    public function tapsList(Request $request){
//        $data = $request->param();
//        $validate = validate('Users');
//        $res = $validate->scene('taps')->check($data);
//        if (!$res){
//            return apistatus(0,$validate->getError());
//        }
//        $list = Db::table('rd_home_taps')
//            ->field('id,name')
//            ->where('type',$data['taptype'])
//            ->where('status',1)
//            ->select();
//        if (!empty($list)){
//            return apistatus(1,'成功',$list);
//        }else{
//            return apistatus(0,'无数据');
//        }
//    }

    /**
     * 附件上传
     * @param string $from 来源
     * @param string $group 附件分组,默认sys[系统]，模块格式：m_模块名，插件：p_插件名
     * @param string $water 水印，参数为空默认调用系统配置，no直接关闭水印，image 图片水印，text文字水印
     * @param string $thumb 缩略图，参数为空默认调用系统配置，no直接关闭缩略图，如需生成 500x500 的缩略图，则 500x500多个规格请用";"隔开
     * @param string $thumb_type 缩略图方式
     * @param string $input 文件表单字段名
     * @author 橘子俊 <364666827@qq.com>
     * @return json
     */
    public function upload()
    {
        if (!isset($_FILES['file'])){
            return apistatus(0,'确少file字段');
        }
        $res = files_upload('file','/upload/'.'headicon'.date('Y-m-d',time()));
        if ($res['status']==200){
            $data['path'] = $res['path'][0];
            return apistatus(1,'文件上传成功',$data);
        }
        return apistatus(0,'文件上传失败',$res['error']);
    }


    /**
     * 找回密码
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function findPwd(Request $request){
        $data = $request->param();
        $validate = validate('Users');
        $res = $validate->scene('findpwd')->check($data);
        if (!$res){
            return apistatus(0,$validate->getError());
        }
        $code = $data['code'];
        $oldcode = Db::table('rd_home_code')
            ->field(['id','code','expire_time','phonenum'])
            ->where('phonenum',$data['phonenum'])
            ->where('status',1)
            ->order('create_time desc')
            ->find();
        if ($oldcode['phonenum'] !== $data['phonenum']){
            return apistatus(0,'请输入获取验证码的手机号');
        }
        if (empty($oldcode)){
            return apistatus(0,'验证码过期请重新获取验证码');
        }

        if ( $oldcode['code'] == $code && $oldcode['expire_time']>time()){
            $result = \db('home_users')
                ->where('phonenum',$data['phonenum'])
                ->update(['pwd'=>sha1($data['pwd'])]);
            if ($result){
                //如果新建成功就删除该手机号对应的验证码缓存
                Db::table('rd_home_code')->where('id',$oldcode['id'])->update(['status'=>2]);
                return apistatus(1,'密码更新成功');
            }else{
                return apistatus(0,'新密码与旧密码重复');
            }
        }else{
            return apistatus(0,'验证码过期或错误');
        }
    }

    /**
     * 广场用户列表
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function userList(Request $request){
        $data = $request->param();
//        $validate = validate('Users');
//        $res = $validate->scene('findpwd')->check($data);
//        if (!$res){
//            return apistatus(0,$validate->getError());
//        }
        if (!empty($data['id'])){
            $this->checktoken($data['id']);
            $self = \db('home_users')
                ->where('id',$data['id'])
                ->field('latitude,longitude,gender,role,purpose')
                ->find();
            $where['id'] = ['neq',$data['id']];

        }else{
            $self['longitude'] = '';
            $self['latitude'] = '';
            $self['gender'] = '';
            $self['role'] = '';
        }
        $where['marriage'] = ['in',[1,2]];
        isset($data['page']) ? $page = $data['page'] : $page = 1;
        isset($data['range']) ? $range = $data['range'] : $range = 200;
        isset($data['listrow']) ? $rows = $data['listrow'] : $rows = 20;
        if ($data['role'] == 1){
            if ($self['role'] == 1 && $self['gender'] == 1){
                $where['gender'] = 2;
            }elseif($self['role'] == 1 && $self['gender'] == 2){
                $where['gender'] = 1;
            }else{
                $where['gender'] = ['in',[1,2]];
            }
            $where['role'] = $data['role'];
            if (!empty($self['longitude']) && !empty($self['latitude'])){
                $req = getSquarePoint($self['longitude'],$self['latitude'],intval($range));
                $long = [$req['right_top']['lng'],$req['left_top']['lng']];
                $lati = [$req['left_bottom']['lat'],$req['left_top']['lat']];
                $where['latitude'] = ['between',$lati];
                $where['longitude'] = ['between',$long];
                $lists =\model('user')
                    ->where($where)
                    ->field('id,nickname,headicon,gender,age,address,salary,latitude,longitude,monologue,role,operation_time')
                    ->select();
                foreach ($lists as $k=>$v){
                    $distance = getDistanceKm($self['longitude'],$self['latitude'],$v['longitude'],$v['latitude']);
                    $lists[$k]['distance'] = sprintf("%.2f", $distance);
                    if ($v['operation_time'] > (time()-300)){
                        $lists[$k]['online'] = '在线';
                    }else{
                        $lists[$k]['online'] = '离线';
                    }
                }
                $count = count($lists);
                for ($i = 0;$i<$count;$i++){
                    for($j=$i+1;$j<$count;$j++){
                        if($lists[$i]['distance']>$lists[$j]['distance']){
                            $temp = $lists[$i];
                            $lists[$i] = $lists[$j];
                            $lists[$j] = $temp;
                        }
                    }
                }
            }else{
                $lists = [];
                $list =\model('user')
                    ->where($where)
                    ->field('id,nickname,headicon,gender,age,address,
                    salary,latitude,longitude,monologue,role,operation_time')
                    ->order('operation_time desc')
                    ->select();
                foreach ($list as $k=>$v){
                    $list[$k]['distance'] = '未知';
                    if ($v['operation_time'] > (time()-300)){
                        $list[$k]['online'] = '在线';
                    }else{
                        $list[$k]['online'] = '离线';
                    }
                    $lists[] = $list[$k]->getData();
                }
            }
//        var_dump($list);die;
            $start=($page-1)*$rows;//偏移量，当前页-1乘以每页显示条数
            if (!empty($lists)){
                $lis['data'] = array_slice($lists,$start,$rows);
            }else{
                $lis['data'] = '';
            }

        }else{
           $lis = \model('User')->alias('U')->where('U.role',$data['role'])
               ->field("U.headicon,U.nickname,U.id,U.operation_time,U.gender,U.age,U.introduction,U.address,U.skills,U.role,
               (select count(*) from rd_home_chats C where C.toid=U.id) as chatcount,
               (select count(*) from rd_home_follow F where F.followdid=U.id) as followcount")
               ->order('chatcount desc,followcount desc,operation_time desc')
               ->paginate($rows,true,['page'=>$page])
               ->each(function ($item){
                   if ($item['operation_time'] > (time()-300)){
                       $item['online'] = '在线';
                   }else{
                       $item['online'] = '离线';
                   }
                   $array = explode(',',$item['skills']);
                   $skill['id'] = ['in',$array];
                   $skill['type'] = $item['role'];
                   $skill['status'] = 1;
                   $skills = \db('home_taps')->where($skill)->field('id skillid,name skillname')->limit(3)->select();
                   $cost['C.tapid'] = $skills[0]['skillid'];
                   $cost['C.uid'] = $item['id'];
                   $cost['C.status'] = 1;
                   $tapcost = \db('home_tapcost')->alias('C')->join('home_taps T','C.tapid=T.id')->where($cost)->field('C.id costid,C.cost,T.name tapname')->limit(1)->find();
                   $item['tapcost'] = $tapcost;
                   $item['skills'] = $skills;
                   return $item;
               });


        }
//        $where['operation_time'] = ['gt',(time()-600)];
        return apistatus(1,'列表获取成功',$lis);

    }




    /**
     * 查看用户资料

     */
    public  function getUserinfo(Request $request)
    {
        $data = $request->param();
        $validate = validate('Users');
        $res = $validate->scene('getuserinfo')->check($data);
        if (!$res){
            return apistatus(0,$validate->getError());
        }
        $where['id'] = $data['uid'];
//        $fobid = \db('home_forbid')->where('')
        $field = "id,headicon,marriage,tall,jobs,education,skills,native_place,age,salary,monologue,wechat_num,address,weight,nickname,gender,operation_time,role";
        $info = User::where('id',$data['uid'])
            ->field($field)
            ->find()
            ->toArray();
        if (empty($info)){
            return apistatus(0,'无用户数据');
        }
        if ($info['role'] == 1){
            $mseeking = \db('home_squares')
                ->where(['uid'=>$data['uid'],'type'=>1])
                ->field('pics1,contents')
                ->order('create_time desc')
                ->find();
            $taps['id'] = ['in',explode(',',$info['skills'])];
            $skills = \db('home_taps')
                ->where($taps)
                ->field('id tapid,name tapname')
                ->select();
            $dynamic = \db('home_squares')
                ->where(['uid'=>$data['uid'],'type'=>4])
                ->field('pics1,contents')
                ->order('create_time desc')
                ->find();
            $dynamic['pics1'] = explode(',',$dynamic['pics1']);
            $mseeking['pics1'] = explode(',',$mseeking['pics1']);
            $pic = \db('home_photos')
                ->where(['uid'=>$data['uid']])
                ->field('pics')
                ->select();
            $info['mseeking'] = $mseeking;
            $info['dynamic'] = $dynamic;
            $info['pics'] = $pic;
            $info['skills'] = $skills;
            $info['isfriend'] = isset($data['id']) ?  isfriend($data['id'],$info['id']) :  0;
            $info['ischat'] = isset($data['id']) ?  isChat($data['id'],$info['id']) :  0;
        }elseif($info['role'] == 2 || $info['role'] == 3){
            $field = "id,headicon,wechat_num,address,nickname,gender,introduction,phonenum,honor,skills,pics2";
            $info = User::where('id',$data['uid'])
                ->field($field)
                ->find()
                ->toArray();
            $taps['C.tapid'] = ['in',explode(',',$info['skills'])];
            $taps['C.uid'] = $data['uid'];
            $skills = \db('home_tapcost')->alias('C')
                ->join('home_taps T','C.tapid=T.id')
                ->where($taps)
                ->field('C.id priceid,C.tapid,C.cost,T.name tapname')
                ->select();
            $pics = [];
                foreach (explode(',',$info['pics2']) as $i=>$j){
                    if (!empty($j)){
                        $pics[] = $j;
                    }else{
                        continue;
                    }
            }
            $info['giftcount'] = getGiftcount($info['id']);
            $info['followcount'] = getFollowcount($info['id']);
            $info['isfollow'] = isset($data['id']) ? isFollow($data['id'],$info['id']) : 0;
            $info['isconsult'] = isset($data['id']) ? isConsult($data['id'],$info['id']) : 0;
            $info['chatcount'] = \db('home_chats')->where(['type'=>3,'toid'=>$info['id']])->group('fromid')->count();;
            $info['skills'] = $skills;
            $info['pics2'] = $pics;
        }
        if ($info){
            return apistatus(1,'数据获取成功',$info);
        }else{
            return apistatus(0,'未获取到数据');
        }
    }
    /**
     * 查看个人资料

     */
    public  function getMyinfo(Request $request)
    {
        $data = $request->param();
//        $validate = validate('Users');
//        $res = $validate->scene('myinfo')->check($data);
//        if (!$res){
//            return apistatus(0,$validate->getError());
//        }
        self::checktoken($data['id']);
        $where['id'] = $data['id'];
        $role = User::where('id',$data['id'])
            ->find()
            ->getAttr('role');
        if ($role == 1){
            $field = "headicon,nickname,wechat_num,tall,weight,age,gender,phonenum,
            native_place,jobs,education,salary,marriage,address,skills,monologue,idcardfront,idcardback";
        }else{
            $field = "headicon,nickname,education,jobs,age,gender,skills,address,phonenum,wechat_num,
            introduction,honor,idcardfront,idcardback,quality_verifi4,quality_verifi3,quality_verifi2,quality_verifi1,pics2";
        }
        $info = \model('user')->where('id',$data['id'])->field($field)->find();
        if (!empty($info['pics2'])){
            $pics = [];
            foreach (explode(',',$info['pics2']) as $i=>$j){
                if (!empty($j)){
                    $pics[] = $j;
                }else{
                    continue;
                }
            }
            $info['pics2'] = $pics;
        }
        if (!empty($info)){
            return apistatus(1,'用户信息获取成功',$info);
        }else{
            return apistatus(0,'用户信息不存在');
        }
    }


    /**
     * 更新个人资料

     */
     public  function updateMyinfo(Request $request)
     {
         $data = $request->param();
         //头像
         if (isset($data['id']) && !empty($data['id'])){
             $id = $data['id'];
             $update['id'] = $id;
         }else{
             return apistatus(0,'用户id不能为空');
         }
         self::checktoken($id);
         if (isset($data['headicon'])){
             $update['headicon'] = $data['headicon'];
         }
         if (isset($data['nickname'])){
             $update['nickname'] = $data['nickname'];
         }
         if (isset($data['wechat_num'])){
             $update['wechat_num'] = $data['wechat_num'];
         }
         if (isset($data['tall'])){
             $update['tall'] = $data['tall'];
         }
         if (isset($data['weight'])){
             $update['weight'] = $data['weight'];
         }
         if (isset($data['honor'])){
             $update['honor'] = $data['honor'];
         }
         if (isset($data['pics2'])){
             $update['pics2'] = $data['pics2'];
         }
         if (isset($data['age'])){
             $update['age'] = $data['age'];
         }
         if (isset($data['jobs'])){
             $update['jobs'] = $data['jobs'];
         }
         if (isset($data['education'])){
             $update['education'] = $data['education'];
         }
         if (isset($data['native_place'])){
             $update['native_place'] = $data['native_place'];
         }
         if (isset($data['salary'])){
             $update['salary'] = $data['salary'];
         }
         if (isset($data['marriage'])){
             $update['marriage'] = $data['marriage'];
         }
         if (isset($data['address'])){
             $update['address'] = $data['address'];
         }
         if (isset($data['skills'])){
             $update['skills'] = $data['skills'];
         }
         if (isset($data['monologue'])){
             $update['monologue'] = $data['monologue'];
         }
         if (isset($data['quality_verifi4'])){
             $update['quality_verifi4'] = $data['quality_verifi4'];
         }
         if (isset($data['quality_verifi1'])){
             $update['quality_verifi1'] = $data['quality_verifi1'];
         }
         if (isset($data['quality_verifi2'])){
             $update['quality_verifi2'] = $data['quality_verifi2'];
         }
         if (isset($data['quality_verifi3'])){
             $update['quality_verifi3'] = $data['quality_verifi3'];
         }
         if (isset($data['idcardfront'])){
             $update['idcardfront'] = $data['idcardfront'];
         }
         if (isset($data['idcardback'])){
             $update['idcardback'] = $data['idcardback'];
         }
         if (isset($data['alipaynum'])){
             $update['alipaynum'] = $data['alipaynum'];
         }
         if (isset($data['realname'])){
             $update['realname'] = $data['realname'];
         }
         if (isset($data['introduction'])){
             $update['introduction'] = $data['introduction'];
         }
         if (isset($data['pics1'])){
             $update['pics1'] = $data['pics1'];
         }
         if (isset($data['purpose'])){
             $update['purpose'] = $data['purpose'];
         }
         if (empty($update)){
             return apistatus(1,'未提交更新数据');
         }
         $res = User::update($update);
         if ($res){
             if (!empty($update['skills'])){
                 $costwhere['uid'] = $id;
                 $costwhere['tapid'] = ['not in',explode(',',$update['skills'])];
                 $oldcost = \db('home_tapcost')->where('uid',$id)->column('tapid');

                 $nowarray = array_merge($oldcost,explode(',',$update['skills']));
                 $difarray = array_diff($nowarray,$oldcost);
                 \db('home_tapcost')->where($costwhere)->delete();

                 if (!empty($difarray)){
                     foreach ($difarray as $k=>$v){
                         $insert[$k]['tapid'] = $v;
                         $insert[$k]['create_time'] = time();
                         $insert[$k]['uid'] = $id;
                         $insert[$k]['cost'] = 400;
                     }
                     \db('home_tapcost')->insertAll($insert);
                 }
                 return apistatus(1,'信息保存成功');
             }
             return apistatus(1,'信息保存成功');
         }else{
             return apistatus(0,'保存失败请重试');
         }


    }
    /**
     * 我关注的用户

     */
    public  function myFollow(Request $request)
    {
        $data = $request->param();
        $validate = validate('Users');
        $res = $validate->scene('follow')->check($data);
        if (!$res){
            return apistatus(0,$validate->getError());
        }
        isset($data['listrow']) ? $data['listrow'] : $data['listrow'] = 7;
        $where['F.uid'] = $data['id'];
       if ($data['role'] == 2){
           $where['U.role'] = 2;
       }else{
           $where['U.role'] = 3;
       }
       $lists = Db::table('rd_home_follow')->alias('F')
           ->join('home_users U','F.followdid = U.id')
           ->where($where)
           ->field('F.id,F.uid,F.followdid,U.nickname followdname,
           U.operation_time,U.gender,U.age,U.address,U.skills,
           U.introduction,U.headicon,U.honor,U.role')
           ->order('F.create_time desc')
           ->paginate($data['listrow'])
           ->each(function ($item){
               if ($item['operation_time'] > (time()-300)){
                   $item['online'] = '在线';
               }else{
                   $item['online'] = '离线';
               }
               $array = explode(',',$item['skills']);
               $skill['id'] = ['in',$array];
               $skill['type'] = $item['role'];
               $skill['status'] = 1;
               $skills = \db('home_taps')->where($skill)->field('id skillid,name skillname')->limit(3)->select();
               $cost['C.tapid'] = $skills[0]['skillid'];
               $cost['C.uid'] = $item['id'];
               $cost['C.status'] = 1;
               $tapcost = \db('home_tapcost')->alias('C')->join('home_taps T','C.tapid=T.id')->where($cost)->field('C.id costid,C.cost,T.name tapname')->limit(1)->find();
               $item['tapcost'] = $tapcost;
               $item['skills'] = $skills;
               if ($item['gender'] == 1){
                   $item['gender'] = '男';
               }else{
                   $item['gender'] = '女';
               }
               return $item;
           });
       if (!empty($lists)){
           return apistatus(1,'列表获取成功',$lists);
       }else{
           return apistatus(0,'不存在对应数据');
       }
    }



    /**
     * 申请添加好友

     */
    public  function applyFriend(Request $request)
    {
        $data = $request->param();
        $insert['fromid'] = $data['fromid'];
        $insert['toid'] = $data['toid'];
        $insert['create_time'] = time();
        $time = ['between',[mktime(0,0,0,date('m'),date('d'),date('Y')),mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1]];
        $apply = \db('home_apply')->where(['fromid'=>$data['fromid'],'toid'=>$data['toid'],'create_time'=>$time])->count();
        if (count($apply)> 3) return apistatus(0,'您本日添加该好友次数过于频繁,请等待对方操作');
        $result = \db('home_apply')->insert($insert);
        if ($result){
            $insert['news_content'] = '申请添加你为好友';
            $insert['type'] = 1;
            \db('home_news')->insert($insert);
            //调用消息推送接口
            return apistatus(1,'好友申请成功');
        }else{
            return apistatus(0,'申请失败请重试');
        }
    }


    /**
     * 申请添加好友
     */
    public  function acceptFriend(Request $request)
    {
        $data = $request->param();
        if ($data['type'] == 1){
            $insert['uid'] = $data['id'];
            $insert['friendid'] = $data['friendid'];
            $insert['create_time'] = time();
            $result = \db('home_friends')->insert($insert);
            if ($result){
                \db('home_apply')
                    ->where(['fromid'=>$data['id'],'toid'=>$data['friendid']])
                    ->update(['status'=>3]);
                $news['fromid'] = $data['id'];
                $news['toid'] = $data['friendid'];
                $news['news_content'] = '同意你的好友申请';
                $news['create_time'] = time();
                $news['type'] = 1;
                \db('home_news')->insert($news);
                $insert['uid'] = $data['friendid'];
                $insert['friendid'] = $data['id'];
                \db('home_friends')->insert($insert);
                return apistatus(1,'好友添加成功');
            }else{
                return apistatus(0,'申请失败请重试');
            }
        }elseif($data['type'] == 2) {
            \db('home_apply')
                ->where(['fromid'=>$data['id'],'toid'=>$data['friendid']])
                ->update(['status'=>4]);
            $news['fromid'] = $data['id'];
            $news['toid'] = $data['friendid'];
            $news['news_content'] = '拒绝了你的好友申请';
            $news['create_time'] = time();
            $news['type'] = 1;
            \db('home_news')->insert($news);
            return apistatus(1,'拒绝成功');
        }

    }




    /**
     * 个人中心消息列表
     */
    public  function newsList(Request $request)
    {
        $data = $request->param();
        $list = \db('home_news')->alias('N')
            ->join('home_users U','N.fromid=U.id')
            ->where('N.toid',$data['id'])
            ->order('N.create_time desc,N.status asc')
            ->field('N.id,N.fromid,U.nickname fromname,N.toid,N.news_content,N.create_time')
            ->paginate(10)->each(function ($item){
                \db('home_news')->where('id',$item['id'])->update(['status'=>2]);
                \db('home_apply')->where('toid',$item['toid'])->update(['status'=>2]);
                return $item;
            });
        if ($list){
            return apistatus(1,'列表获取成功',$list);
        }else{
            return apistatus(0,'无新消息');
        }
    }


    //邀请伙伴
    public function sharePartner(Request $request){
        $data = $request->param();
        if (!isset($data['id']) || empty($data['id'])){
            return apistatus(0,'用户id未提交或不存在');
        }
        $id = $data['id'];
        $invicode = Db::table('rd_home_users')->where('id',$id)->field('invicode,role')->find();
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 6;//生成图片大小
        $url = localhostbd()."/theme/register/register.php?invicode={$invicode['invicode']}";
        //生成二维码图片
        \QRcode::png($url, "qrcode.png", $errorCorrectionLevel, $matrixPointSize, 2);
        $logo = EXTEND_PATH."logo/redbeanlogo.png";//准备好的logo图片
        $QR ="qrcode.png";//已经生成的原始二维码图
        if ($logo !== FALSE) {
            $QR = imagecreatefromstring(file_get_contents($QR));
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);//二维码图片宽度
            $QR_height = imagesy($QR);//二维码图片高度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width/$logo_qr_width;
            $logo_qr_height = $logo_height/$scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                $logo_qr_height, $logo_width, $logo_height);
        }
        $fileName=md5($url);
        $EchoPath="/upload/share/".$fileName.'.png';
        imagepng($QR,ROOT_PATH.$EchoPath);
        imagedestroy($QR);
        $output['url'] = $url;
        $output['src'] = $EchoPath;
        if ($invicode['role'] == 1){
            $output['bgsrc'] =config('base.site_domain')."/extend/logo/invitefriend.png";
        }else{
            $output['bgsrc'] =config('base.site_domain')."/extend/logo/invite.png";
        }


        return apistatus(1,'邀请页创建成功',$output);
    }
    public function followme(Request $request){
        $data = $request->param();
        self::checktoken($data['id']);
        $where['F.followdid'] = $data['id'];
        isset($data['page']) ? $page = $data['page'] : $page = 1;
        isset($data['listrow']) ? $listrow = $data['listrow'] : $listrow = 1;
        $userslist = \db('home_follow')
            ->alias('F')
            ->join('home_users U','F.uid = U.id')
            ->where($where)
            ->field('F.uid fromid,U.nickname,U.headicon,U.monologue')
            ->paginate($listrow,true,['page'=>$page]);
            return apistatus(1,'获取成功',$userslist);
    }

    //一键创建invicode
//    public function createInvicode(){
//        $data = Db::table('rd_home_users')->field('id')->select();
//        foreach ($data as $k=>$v){
//
//                $code = randCode();
//                Db::table('rd_home_users')->where('id',$v['id'])->update(['invicode'=>$code]);
//        }
//    }

//一键创建invicode

    //获取注册协议
    public function getRegisterProtocle(){
        $pro = \db('home_articles')->order('update_time desc')->find();
        if ($pro){
            return apistatus(1,'获取成功',$pro);
        }else{
            return apistatus(0,'无数据');
        }
    }
    //获取用户动态详情
    public function getUsersquares(Request $request){
        $data = $request->param();
        if (empty($data['uid'])){
            return apistatus(0,'用户信息缺失');
        }
        empty($data['page']) ? $page = 1 : $page = $data['page'];
        empty($data['listrow']) ? $listrow = 15 : $listrow = $data['listrow'];
        $where['uid'] = $data['uid'];
        if ($data['type'] == 1){
           $where['pics1'] = ['neq',''];
            $pro = \db('home_squares')->where($where)->field('pics1')->paginate($listrow,true,['page'=>$page]);
            $list = $pro->toarray();
            $lists = [];
            foreach ($list['data'] as $k=>$value){
                $arra = explode(',',$value['pics1']);
                foreach ($arra as $i=>$j){
                    if (!empty($j)){
                        $lists[] = $j;
                    }
                }
            }
        }elseif($data['type'] == 2){
            $where['type'] = 4;
        }else{
            $where['type'] = 1;
        }
        $lists = \db('home_squares')
            ->alias('S')
            ->join('home_users U',"S.uid=U.id")
            ->field('S.id,S.uid,S.contents,S.pics1,S.type,S.skills,S.longitude,S.latitude,S.create_time,S.is_top,
            U.gender,U.nickname,U.role,U.age,U.address uaddress,S.saddress,U.operation_time,U.headicon')
            ->order('S.is_top desc,S.create_time desc')
            ->where($where)
            ->paginate($listrow,true,['page'=>$page])
            ->each(function ($item){
                $item['countpraise'] = countPraises($item['id']);
                if ($item['operation_time'] > (time()-300)){
                    $item['opstatus'] = '在线';
                }else{
                    $item['opstatus'] = '离线';
                }
                $item['pics1'] = explode(',',$item['pics1']);
                return $item;
            });
        $lists = $lists->toarray();
        if (!empty($lists)){
            if (!empty($id)){
                $langlati = \db('home_users')
                    ->where('id',$id)
                    ->field('longitude,latitude')
                    ->find();
            }else{
                $langlati['latitude'] = '';
                $langlati['longitude'] = '';
            }
            foreach ($lists['data'] as  $k=>$v){
                $is_praise = isPraise($data['id'],$v['id']);
                $lists['data'][$k]['is_praise'] = $is_praise;
                if (empty($langlati['latitude']) || empty($v['longitude'])){
                    $lists['data'][$k]['distance'] = '未知';
                    continue;
                }
                $distance = getDistanceKm($langlati['longitude'],$langlati['latitude'],$v['longitude'],$v['latitude']);
                $lists['data'][$k]['distance'] = sprintf("%.2f", $distance);
            }
            return apistatus(1,'列表获取成功',$lists);
        }else{
            return apistatus(0,'无数据');
        }
    }

}
